package com.jic.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.mapper.MStoreVirtualMapper;
import com.jic.product.mapper.MStoreVirtualRelMapper;
import com.jic.product.mapper.MStoreVirtualShopRelMapper;
import com.jic.product.model.entity.MStore;
import com.jic.product.model.entity.MStoreVirtual;
import com.jic.product.model.entity.MStoreVirtualRel;
import com.jic.product.model.entity.MStoreVirtualShopRel;
import com.jic.product.model.vo.request.MStoreVirtualRequest;
import com.jic.product.model.vo.response.MStoreResponse;
import com.jic.product.model.vo.response.MStoreVirtualResponse;
import com.jic.product.service.MStoreVirtualService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class MStoreVirtualServiceImpl implements MStoreVirtualService {

    @Resource
    private MStoreVirtualMapper mapper;

    @Resource
    private MStoreVirtualRelMapper mStoreVirtualRel;

    @Resource
    private MStoreVirtualShopRelMapper mStoreVirtualShopRelMapper;


    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(MStoreVirtualRequest request) {
        MStoreVirtual mStoreVirtual = new MStoreVirtual();
        BeanUtils.copyProperties(request, mStoreVirtual);
        mStoreVirtual.setDeptId(request.getAdminOperate().getDeptId());
        mStoreVirtual.setCreateTime(new Date());
        mStoreVirtual.setCreator(request.getAdminOperate().getOperator());
        int flag = mapper.insert(mStoreVirtual);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }


    /**
     * 保存或修改记录信息
     *
     * @param requests 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    @Transactional
    public int saveOrUpdate(MStoreVirtualRequest requests) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(requests));
        try {
            if (requests == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (requests.getId() != null && requests.getId() != 0) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(requests));
                MStoreVirtual request = new MStoreVirtual();
                BeanUtils.copyProperties(requests, request);
                request.setUpdateTime(new Date());
                request.setUpdater(request.getAdminOperate().getOperator());
                request.setDeleteFlag(0);
                //修改仓库基本信息
                int flag = mapper.updateByPrimaryKey(request);
                //修改虚拟仓库和实体仓库 店铺 关联关系
                List<MStoreVirtualRel> shops = request.getShops();
                List<MStoreVirtualRel> warehouses = request.getWarehouses();
                if (null != shops && shops.size() > 0) {
                    for (MStoreVirtualRel shop : shops) {
                        if (shop.getId() != null && shop.getId() != 0) {
                            //更新
                            mStoreVirtualRel.updateByPrimaryKeySelective(shop);
                        } else {
                            //新增一条记录
                            Long id = shop.getId();
                            shop.setStoreId(id);
                            shop.setId(null);
                            shop.setVitualId(request.getId());
                            shop.setDeleteFlag(0);
                            shop.setStoreType(2L);
                            int i = mStoreVirtualRel.insertSelective(shop);
                        }
                    }
                }
                if (null != warehouses && warehouses.size() > 0) {
                    for (MStoreVirtualRel warehouse : warehouses) {
                        if (warehouse.getId() != null && warehouse.getId() != 0) {
                            //更新
                            warehouse.setVitualId(request.getId());
                            mStoreVirtualRel.updateByPrimaryKeySelective(warehouse);
                        } else {
                            //新增一条记录
                            Long id = warehouse.getId();
                            warehouse.setId(null);
                            warehouse.setVitualId(request.getId());
                            warehouse.setDeleteFlag(0);
                            warehouse.setStoreType(1L);
                            int i = mStoreVirtualRel.insertSelective(warehouse);
                        }
                    }
                }
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(requests));
                MStoreVirtual request = new MStoreVirtual();
                BeanUtils.copyProperties(requests, request);
                request.setCreator(request.getAdminOperate().getOperator());
                request.setCreator(request.getAdminOperate().getOperator());
                request.setCreateTime(new Date());
                //新增虚拟仓库主体信息
                request.setDeleteFlag(0);
                int flag = mapper.insertSelective(request);
                if (request.getId() != null) {
                    //保存虚拟仓库和实体仓库 店铺 关联关系
                    List<MStoreVirtualRel> shops = request.getShops();
                    List<MStoreVirtualRel> warehouses = request.getWarehouses();
                    if (null != shops && shops.size() > 0) {
                        for (MStoreVirtualRel shop : shops) {
                            Long id = shop.getId();
                            shop.setStoreId(id);
                            shop.setId(null);
                            shop.setVitualId(request.getId());
                            shop.setDeleteFlag(0);
                            shop.setStoreType(2L);
                            int i = mStoreVirtualRel.insertSelective(shop);
                        }
                    }
                    if (null != warehouses && warehouses.size() > 0) {
                        for (MStoreVirtualRel warehouse : warehouses) {
                            Long id = warehouse.getId();
                            warehouse.setId(null);
                            warehouse.setVitualId(request.getId());
                            warehouse.setDeleteFlag(0);
                            warehouse.setStoreType(1L);
                            int i = mStoreVirtualRel.insertSelective(warehouse);
                        }
                    }
                }
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(MStoreVirtual request) {
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(MStoreVirtual request) {
        request.setDeleteFlag(1);
        int flag = mapper.updateByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(MStoreVirtual request) {
        try {
            log.info("修改记录");
            MStoreVirtual param = new MStoreVirtual();
            BeanUtils.copyProperties(request, param);
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public MStoreVirtual getByPrimaryKey(MStoreVirtual request) {
        MStoreVirtual mStoreVirtual = mapper.selectByPrimaryKey(request);
        //查询虚拟店铺关联的实体仓库 店铺
        MStoreVirtualRel params = new MStoreVirtualRel();
        params.setVitualId(mStoreVirtual.getId());
        params.setStoreType(1L);
        List<MStoreVirtualRel> wares = mStoreVirtualRel.selectBySelective(params);
        params.setStoreType(2L);
        List<MStoreVirtualRel> shops = mStoreVirtualRel.selectBySelective(params);
        mStoreVirtual.setShops(shops);
        mStoreVirtual.setWarehouses(wares);
        return mStoreVirtual;
    }


    /**
     * 分页查询
     *
     * @param request 分页查询入参实体类
     * @return 含有分页信息的实体类列表
     */
    @Override
    public PageResult<MStoreVirtualResponse> listPageBySelective(MStoreVirtualRequest request, int pageNum, int pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        List<MStoreVirtual> mStoreVirtuals = null;
        List<MStoreVirtual> rels = null;
        PageHelper.orderBy(" create_time desc");

        if (request.getWarehouseId() != null && request.getWarehouseId() > 0) {
            MStoreVirtualRel virtualRel = new MStoreVirtualRel();
            virtualRel.setDeleteFlag(0);
            virtualRel.setStoreId(request.getWarehouseId());
            if(request.getAdminOperate().getDeptType().getCode()!=0){
                virtualRel.setDeptId(request.getAdminOperate().getDeptId());
            }
            mStoreVirtuals = this.mapper.queryTheVirtualWarehouseWithTheStore(virtualRel);

        }else if (request.getShopId() != null && request.getShopId() > 0) {
            MStoreVirtualShopRel virtualRel = new MStoreVirtualShopRel();
            virtualRel.setDeleteFlag(0);
            virtualRel.setShopId(request.getStoreId());
            if(request.getAdminOperate().getDeptType().getCode()!=0){
                virtualRel.setDeptId(request.getAdminOperate().getDeptId());
            }
            rels = this.mapper.queryVirtualStorehouseWithPhysicalStorehouse(virtualRel);
        }else{
            //获取所以的虚拟仓库
            mStoreVirtuals = mapper.listPageBySelective(request);
        }
        if (rels!=null && mStoreVirtuals!=null){
            if (rels.size()>0 && mStoreVirtuals.size()>0){
                mStoreVirtuals.removeAll(rels);
                //mStoreVirtuals将rels中的值进行添加
                mStoreVirtuals.addAll(rels);
            }
        }
//        ids1.removeAll(ids2);
//        ids1.addAll(ids2);
//        request.setVaIds(ids1);
//        if (request.getAdminOperate().getDeptType().getCode() != 0) {
//            request.setDeptId(request.getAdminOperate().getDeptId());
//        }
//        List<MStoreVirtual> mStoreVirtuals = mapper.listPageBySelective(request);
        PageInfo<MStoreVirtual> pageInfo = new PageInfo<>(mStoreVirtuals);
        List<MStoreVirtualResponse> collect = null;
        PageResult<MStoreVirtualResponse> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        if (pageInfo.getList()!=null){
            collect = pageInfo.getList().stream().map(temp -> {
                MStoreVirtualResponse bo = new MStoreVirtualResponse();
                BeanUtils.copyProperties(temp, bo);
                return bo;
            }).filter(item -> item != null).collect(Collectors.toList());
            result.setRows(collect);
        }

        return result;
    }

    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<MStoreVirtual> listAllRecord(MStoreVirtual request) {
        //分页处理
        request.setDeleteFlag(0);
        return mapper.selectBySelective(request);
    }


}
